//
//  TSZNewFeatureCollectionViewController.swift
//  微博天下
//
//  Created by Tsz on 15/10/11.
//  Copyright © 2015年 Tsz. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

//类
class TSZNewFeatureCollectionViewController: UICollectionViewController {
    /**
    图像总数
    */
    private let imageCount = 4
    
    //布局属性
    private let layout = TSZLatout()
    //初始化layout 不然报错
    init(){
        super.init(collectionViewLayout:layout)
    }
    required init?(coder aDecoder: NSCoder) {
        
//        fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册cell
        self.collectionView?.registerClass(newFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

// MARK uicolletionView的数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
       
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! newFeatureCell
        
        cell.imageIndex = indexPath.item
    
        return cell
    }
    
    //完成cell「 - indexPath之前消失」 ， 
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //获取当前显示的indexPath
        let path = collectionView.indexPathsForVisibleItems().last!
        
        //判断是否是末尾
        if path.item == imageCount - 1 {
            //播放动画
            let cell = collectionView.cellForItemAtIndexPath(path) as! newFeatureCell
            
            cell.startButtonAnim()
        }
    }

}
    //类
 /// 新特性的cell ，相当于在oc中自定义的一个类
class newFeatureCell:UICollectionViewCell{
        //图像的索引
        private var imageIndex: Int = 0 {
            didSet {
                iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
                startButton.hidden = true
            }
    }
    
    //开始体验 ，发送通知
    func clickStartButton(){
       NSNotificationCenter.defaultCenter().postNotificationName(TSZRootViewControllerSwitchNotification, object: true)
    }
    
    
    //开始按钮动画
    private func startButtonAnim(){
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        // 禁用按钮操作
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            // 恢复默认形变
            self.startButton.transform = CGAffineTransformIdentity
            
            }) { (_) -> Void in
                // 启用按钮点击
                self.startButton.userInteractionEnabled = true
        }
    }
            //MARK: - 设置UI
    override init(frame: CGRect){
        super.init(frame: frame)
        prepareUI()

    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        prepareUI()

    }
    //准备UI
    private func  prepareUI(){
    //添加控件
        contentView.addSubview(iconView)
        
        contentView.addSubview(startButton)
        iconView.ff_Fill(contentView)
        
        
        startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: contentView, size: nil, offset: CGPoint(x: 0, y: -160))
    }
    
   
    ///MARK: - 懒加载图片
    private lazy var iconView = UIImageView()
    private lazy var startButton: UIButton = {
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.setTitle("开始体验", forState: UIControlState.Normal)
        // 根据背景图片自动调整大小
        button.sizeToFit()
        
        // 提示: 按钮的隐藏属性会因为复用工作不正常
        button.hidden = true
        
        button.addTarget(self, action: "clickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
        }()
    }

    
    //类
/// 自定义流水式布局
    private class TSZLatout:UICollectionViewFlowLayout{
        //注意方法  prepareLayout : 准备布局 ，如果还没有设置 layout，获取数量之后，准备cell之前，会被调用一次
        private override func prepareLayout() {
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            //取消两边的拉伸
            collectionView?.bounces = false
        }
    }
